import 'package:flutter_admin/api/odoo/purchase_evaluation_item_odoo_api.dart';
import 'package:flutter_admin/models/odoo/purchase_evaluation_item.dart';
import 'package:flutter_admin/models/odoo/purchase_evaluation_project.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/odoo/purchase_evaluation_project/purchase_evaluation_item_edit.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';

class PurchaseEvaluationItemLIst extends StatefulWidget {
  PurchaseEvaluationProject? purchaseEvaluationProject;
  PurchaseEvaluationItemLIst(
      {required this.purchaseEvaluationProject, Key? key})
      : super(key: key);

  @override
  _PurchaseEvaluationProjectListState createState() =>
      _PurchaseEvaluationProjectListState();
}

class _PurchaseEvaluationProjectListState
    extends State<PurchaseEvaluationItemLIst> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  PurchaseEvaluationItem purchaseEvaluationItem = PurchaseEvaluationItem();
  List<PurchaseEvaluationItem> selectedList = [];
  var templateName = '';
  var deptName = '';
  var projectName = '';
  var projectId = '';
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  @override
  Widget build(BuildContext context) {
    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(
          label: Text('考核内容'),
        ),
        DataColumn(
          label: Text('评估等级标准'),
        ),
        DataColumn(
          label: Text('权重分数'),
        ),
      ],
      getCells: (m) {
        PurchaseEvaluationItem purchaseEvaluationItem =
            PurchaseEvaluationItem.fromMap(m);
        return [
          DataCell(Text(purchaseEvaluationItem.assessmentContent ?? '--')),
          DataCell(Text(purchaseEvaluationItem.evaluationCriteria ?? '--')),
          DataCell(Text(purchaseEvaluationItem.weightScore != null
              ? purchaseEvaluationItem.weightScore.toString()
              : '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.add(context, () => _edit(null)),
        CryButtons.edit(context,
            selectedList.length != 1 ? null : () => _edit(selectedList[0])),
        CryButtons.delete(context,
            selectedList.length < 1 ? null : () => _delete(selectedList)),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      appBar: AppBar(
        leading: Builder(
          builder: (BuildContext context) {
            final ModalRoute<Object?>? parentRoute = ModalRoute.of(context);
            final bool canPop = parentRoute?.canPop ?? false;

            if (canPop) {
              return BackButton();
            } else {
              return SizedBox.shrink();
            }
          },
        ),
        title: Text('考核内容及标准'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          buttonBar,
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _edit(PurchaseEvaluationItem? purchaseEvaluationItem) async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: PurchaseEvaluationItemEdit(
          purchaseEvaluationItem: purchaseEvaluationItem,
          templateName: templateName,
          deptName: deptName,
          projectName: projectName,
          projectId: projectId,
        ),
      ),
    ).then((v) {
      if (v != null) {
        if(purchaseEvaluationItem == null){
          // 新增时回到第一页
          tableKey.currentState?.pageTo(0);
        }
        _loadData();
      }
    });
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    templateName = widget.purchaseEvaluationProject!.templateName!;
    deptName = widget.purchaseEvaluationProject!.deptName!;
    projectName = widget.purchaseEvaluationProject!.evaluationProject!;
    projectId = widget.purchaseEvaluationProject!.id!;
    purchaseEvaluationItem.projectId = widget.purchaseEvaluationProject!.id;
    ResponseBodyApi responseBodyApi = await PurchaseEvaluationItemOdooApi.page(
        data: {
          "page": page,
          "domainList": purchaseEvaluationItem.toDomainList()
        });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _delete(List<PurchaseEvaluationItem> selectedList) async {
    cryConfirm(context, S.of(context).confirmDelete, (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      var result = await PurchaseEvaluationItemOdooApi.removeByIds(ids);
      if (result.success!) {
        _query();
        CryUtils.message(S.of(Cry.context).success);
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<PurchaseEvaluationItem>(
                (e) => PurchaseEvaluationItem.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.add) {
          _edit(null);
        } else if (v == OperationType.edit) {
          _edit(selectedList[0]);
        } else if (v == OperationType.delete) {
          _delete(selectedList);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          child: ListTile(
            leading: const Icon(Icons.add),
            title: Text('添加'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1,
            title: Text('修改'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length != 0,
          child: ListTile(
            leading: const Icon(Icons.delete),
            enabled: selectedList.length != 0,
            title: Text('删除'),
          ),
        ),
      ],
    );
  }
}
